"""基于协程下载图片"""
import aiohttp
import asyncio

headers = {
    'referer': 'https://w.weipaitang.com/',
    'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) '
                  'Version/13.0.3 Mobile/15E148 Safari/604.1 '
}


async def fetch(session, task):
    url = task.get('url')
    img_name = task.get('name')
    print('发起请求：', url)
    async with session.get(url, headers=headers) as response:
        content = await response.content.read()
        with open(img_name, 'wb') as file_object:
            file_object.write(content)
        print('完成请求：', url)


async def main():
    url_list = [
        {
            'url': 'https://cdn.weipaitang.com/img/20210307fjd9ozhs-p0un-tlyv-xkry-615103380132-W828H1104/w/320',
            'name': '1.jpg'
        },
        {
            'url': 'https://cdn.weipaitang.com/img/20210307rzffiv1x-kolk-k1bv-2ra6-615103384720-W828H1104/w/320',
            'name': '2.jpg'
        },
        {
            'url': 'https://cdn.weipaitang.com/img/202103075ix82ua8-6uj4-qo0f-hp57-615103389455-W828H1104/w/320',
            'name': '3.jpg'
        }
    ]
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.create_task(fetch(session, item)) for item in url_list]
        await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main())
